package com.it.base.common.handler;

import java.util.List;

import org.springframework.jdbc.BadSqlGrammarException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import lombok.extern.slf4j.Slf4j;
import com.it.base.common.constant.SystemConstant;
import com.it.base.common.exception.CommonException;
import com.it.base.common.view.Result;
import com.it.base.common.view.ResultCode;;


/**
 * 统一异常处理类
 */
@Slf4j
@RestControllerAdvice(basePackages = { SystemConstant.BASEPACKAGE })
public class BaseExceptionHandler {

	@ExceptionHandler(value = Exception.class)
	public Result<?> error(Exception e) {
		e.printStackTrace();

		log.debug(e.getClass().toString());

		// 业务
		if (e.getClass() == CommonException.class) {
			CommonException ce = (CommonException) e;
			return new Result<>(ce.getResultCode());
		}

		// sql错误异常
		if (e.getClass() == BadSqlGrammarException.class) {
			return Result.ERROR();
		}

		// 参数校验
		if (e.getClass() == MethodArgumentNotValidException.class) {
			MethodArgumentNotValidException me = (MethodArgumentNotValidException) e;
			BindingResult bindingResult = me.getBindingResult();
			StringBuffer message = new StringBuffer();
			List<FieldError> fieldErrors = bindingResult.getFieldErrors();
			for (FieldError fieldError : fieldErrors) {
				message.append(fieldError.getDefaultMessage()).append(",");
			}
			message.deleteCharAt(message.length() - 1);

			// 返回自定义的异常信息
			ResultCode e999999 = ResultCode.E_999999;
			e999999.setMessage(message.toString());
			return new Result(e999999);
		}

//		// 权限不足
//		if (e instanceof org.springframework.security.access.AccessDeniedException) {
//			return new Result(RCode.E_NO_AUTHORITY);
//		}

		return Result.ERROR();
	}
}
